import Environment, Board, NewNanobot, random, sys, pygame, os, time, Greedybot #@UnresolvedImport

def readFile(task,flag):
    ''' Reads the file specified and generates all the objects required
        specified in the file. It then returns a new grid and the objects
        generated.
    '''
    
    path = sys.path[0]
    file = open(os.path.join(path, "../tasks/",task))
    contents = file.read()
    lines = contents.split("\n")
    dimensions = lines[0].split(" ")
    grid = Board.Grid(int(dimensions[0])/int(dimensions[2]))
    gsize = int(dimensions[2])
    wsize = int(dimensions[0])
    
    randomNumSeed = time.clock()
    botCount =0 
    for line in lines:
        items = line.split(" ")
        if items[0] == "Nanobot":
            botCount += 1
            grid.addObj(NewNanobot.Nanobot( (int(items[2]), int(items[1])), gsize, wsize, randomNumSeed, botCount))

           # grid.addObj(Greedybot.GreedyNanobot( (int(items[2]), int(items[1])), gsize, wsize, randomNumSeed, botCount))
        if items[0] == "Goal":
            grid.addObj(Environment.Goal((int(items[2]), int(items[1])), gsize))
        if items[0] == "Block":
            grid.addObj(Environment.Block((int(items[2]),int(items[1])), gsize))
        if items[0] == "Switch":
            grid.addObj(Environment.Switch((int(items[2]),int(items[1])), gsize))
        if items[0] == "Wall":
            grid.addObj(Environment.Wall((int(items[2]),int(items[1])), gsize))
        grid.botCount = botCount
    return (grid, dimensions) 

    
    

class GameGUI():
    pygame.init()
    Clock = pygame.time.Clock()    

    size = width, height = None, None
    gridsize = None
    nanobots = []
    screen = None
    backgroundcolor = (255,255,255)
    velocity = 5                    # Sets movement per iteration in terms of pixels
                                    # This can also be thought of as the step size
    framerate = 1                   # Max FPS
    
    running = True
    nanovision = False
    viewSeen = -1
    
    def __init__(self, worldGrid, dimensions): 
        ''' Constructor for GameGrid, creates blank lists of objects and sprites,
            and creates the gui screen
        '''
        self.size = self.width, self.height = int(dimensions[0]), int(dimensions[1])
        self.gridsize = int(dimensions[2])
        self.screen = pygame.display.set_mode(self.size)       
        self.grid = worldGrid
        for obj in self.grid.objects:
            if isinstance(obj, NewNanobot.Nanobot):
            #if isinstance(obj, Greedybot.GreedyNanobot):
                self.nanobots.append(obj)
    
    def testStart(self):
        ''' Starts to run the simulation, running a constant loop
            that moves the bots once per time-step and updates the gui
            accordingly.        
        '''
        run = 1
        while run:
            self.Clock.tick(self.framerate)
            self.checkEvents()
            print self.nanobots[0].time
            if self.running:
                for bot in self.nanobots:
                    bot.performAction()
                    self.screen.blit(bot.image,bot.rect)
                self.updateScreen(self.screen)
            run = 0
            for bot in self.nanobots:
                if bot.state != "endrun":
                    run = 1
                    
        print self.nanobots[0].time
        sys.exit()
            

    def checkEvents(self):
        ''' Checks the pygame event queue for quit commands, and any key input.
             Key input changes the system in the following ways:
             Space - Pauses the simulation
             q     - Quits the program
             =     - Increases the framerate
             -     - Decreases the framerate
             v     - Displays the squares knowns by the Nanobots
         '''
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.unicode == " ":
                    self.running = not self.running
                elif event.unicode == "q":
                    pygame.quit()
                    sys.exit()
                elif event.unicode == "=":
                    self.framerate = self.framerate+5
                elif event.unicode == "-":
                    self.framerate = self.framerate-5
                elif event.unicode == "d":
                    self.nanovision = not self.nanovision
                elif event.unicode == "v":
                    if self.viewSeen == len(self.nanobots)-1 :
                        self.viewSeen = -1
                    else:
                        self.viewSeen += 1
                                            
    def updateScreen(self, screen):
        ''' Updates the gui to reflect the positions of all elements '''
        screen.fill(self.backgroundcolor)
        for obj in self.grid.objects:
            obj.rect.topleft = [obj.loc[0]*self.gridsize, obj.loc[1]*self.gridsize]
            if isinstance(obj, Environment.Goal):
                hasBlock = False
                for obj in self.grid.objectsAt(obj.loc):
                    if isinstance(obj, Environment.Block):
                        hasBlock = True
                if not hasBlock:
                    screen.blit(obj.image, obj.rect) 
            else:
                screen.blit(obj.image, obj.rect) 
        # Code for showing vision
        if self.viewSeen>=0:
            for y in range(0, self.grid.size):
                for x in range(0, self.grid.size):
                    # If there are no objects in this square
                    if not self.grid.objectsAt((y,x)):
                        if(self.nanobots[self.viewSeen].internalGrid[y][x].viewed):
                            image = pygame.Surface([self.gridsize, self.gridsize])
                            image.fill((255, 0, 0))
                            screen.blit(image, (self.gridsize * y, self.gridsize * x)) 
        for bot in self.nanobots:
            screen.blit(bot.image, bot.rect)
        pygame.display.flip()